package com.moss.cloud.common.mongo.config;

import com.anwen.mongo.handlers.MetaObjectHandler;
import com.anwen.mongo.model.AutoFillMetaObject;
import com.moss.cloud.common.core.enums.state.Deleted;
import com.moss.cloud.common.core.utils.GenUtil;
import com.moss.cloud.common.core.utils.UserContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.util.Optional;

@Slf4j
@Component
public class CommonMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(AutoFillMetaObject autoFillMetaObject) {
        String username = Optional.ofNullable(UserContextHolder.getUserInfo())
                .filter(userInfo -> UserContextHolder.getAuthStatus().equals(Boolean.TRUE))
                .map(userInfo -> UserContextHolder.getUsername())
                .orElse("system");
        autoFillMetaObject.forceFillValue("_id", GenUtil.nextStrId());
        autoFillMetaObject.forceFillValue("created_by", username);
        autoFillMetaObject.forceFillValue("updated_by", username);
        autoFillMetaObject.forceFillValue("created_time", LocalDateTime.now());
        autoFillMetaObject.forceFillValue("updated_time", LocalDateTime.now());
        autoFillMetaObject.forceFillValue("deleted", Deleted.ENABLE.code());
    }

    @Override
    public void updateFill(AutoFillMetaObject autoFillMetaObject) {
        String username = Optional.ofNullable(UserContextHolder.getUserInfo())
                .filter(userInfo -> UserContextHolder.getAuthStatus().equals(Boolean.TRUE))
                .map(userInfo -> UserContextHolder.getUsername())
                .orElse("system");
        autoFillMetaObject.forceFillValue("updated_by", username);
        autoFillMetaObject.forceFillValue("updated_time", LocalDateTime.now());
    }
}
